import 'dart:io';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/index_page.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

class RouterUtils {

  /// 渐变跳转方式
  static Future routeGradual(BuildContext context, Widget widget) {
    return Navigator.push(context, _GradualRouteBuilder(widget));
  }

  ///带返回值的右进右出的带返回值跳转
  static Future<T> routeForFutureResult<T>(
      BuildContext context, Widget widget,
      {RouteSettings settings, String routeName}) {
    //省缺路由名
    if (StringUtils.isEmpty(routeName)) {
      routeName = widget?.runtimeType?.toString();
    }
    print(
        "\n"
            "------------------------------------------------------------------"
            "\n\n"
            "  路由：>>>>>> 跳转到页面/组件名称：--------- ${widget?.runtimeType?.toString() ?? "未知"}"
            "\n\n"
            "------------------------------------------------------------------"
    );
    return Navigator.push<T>(
        context,
        new _MyCupertinoPageRoute(
            settings: settings ??
                (StringUtils.isNotEmpty(routeName)
                    ? RouteSettings(name: routeName)
                    : null),
            builder: (BuildContext context) {
              return widget;
            }))..then((value){
      try {
        String router = ModalRoute
            ?.of(context)
            ?.settings
            ?.name ?? "未知";
        print(
            "\n"
                "--------------------------------------------------------"
                "\n\n"
                "  路由：<<<<<< 返回当前名称：--------- ${router}"
                "\n\n"
                "-------------------------------------------------------"
        );
        if(AppMain.ROUTER == router){
          ///自动登录逻辑
          Future<int> future = SharePreferenceUtil.getInt(IndexPage.AUTO_LOGIN_TIME);
          future.then((time){
            if(time == null || time < 1){
              UserRepository.getInstance()
                  .loginService(
                  isBackIndexPage: false,
                  callback: VgBaseCallback(onSuccess: (UserDataBean userDataBean) {
                    VgHudUtils.hide(context);
                  }, onError: (String msg) {
                    VgHudUtils.hide(context);
                    if("未登录" != msg){
                      VgToastUtils.toast(context, msg);
                    }
                  }))
                  .autoLogin();
            }else{
              int currentTime = DateTime.now().millisecondsSinceEpoch;
              if(currentTime - time >= 5*60*1000){
                UserRepository.getInstance()
                    .loginService(
                    isBackIndexPage: false,
                    callback: VgBaseCallback(onSuccess: (UserDataBean userDataBean) {
                      VgHudUtils.hide(context);
                    }, onError: (String msg) {
                      VgHudUtils.hide(context);
                      VgToastUtils.toast(context, msg);
                    }))
                    .autoLogin();
              }
            }
          });
        }
      }catch(e){

      }
    });
  }


  ///压出堆栈
  ///优先内部Navigator压出堆栈
  ///无法压出页面时，检测根Navigator时候可以压出
  static void pop<T>(BuildContext context,{T result}){
    if(Navigator.of(context).canPop()){
      Navigator.of(context).pop(result ?? null);
      return;
    }
    if(Navigator.of(context,rootNavigator: true).canPop()){
      Navigator.of(context,rootNavigator: true).pop(result ?? null);
    }
  }

  ///退出至选定路由
  ///rootNavigator: 是否获取根路由
  static void popUntil(BuildContext context,String routeName,{bool rootNavigator = false}){
    if(StringUtils.isEmpty(routeName)){
      return;
    }
    Navigator.of(context,rootNavigator: rootNavigator).popUntil(ModalRoute.withName(routeName));
  }

  ///判断是否能退出
  static bool canPop(BuildContext context){
    if(Navigator.of(context).canPop()){
      return true;
    }
    if(Navigator.of(context,rootNavigator: true).canPop()){
      return true;
    }
    return false;
  }

  ///尽可能压出堆栈 不行则退出app
  static void popOrExit(BuildContext context) async{
    if(Navigator.of(context).canPop()){
      Navigator.of(context).pop();
      return;
    }
    if(Navigator.of(context,rootNavigator: true).canPop()){
      Navigator.of(context,rootNavigator: true).pop();
      return;
    }
    //杀进程
    if(Platform.isIOS){
      exit(0);
    }else if(Platform.isAndroid){
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  }

  ///压入并一直压出
  static Future<T> pushAndRemoveUntil<T>(BuildContext context,Widget widget,String utilRouteName,{String pushRouteName}){
    if(StringUtils.isEmpty(utilRouteName) || widget == null){
      return Future(null);
    }
    //省缺路由名
    if (StringUtils.isEmpty(pushRouteName)) {
      pushRouteName = widget?.runtimeType?.toString();
    }
    return Navigator.of(context).pushAndRemoveUntil<T>(
        _MyCupertinoPageRoute(
            settings: RouteSettings(name: pushRouteName),
            builder: (context) =>widget),
        ModalRoute.withName(utilRouteName));
  }

  ///压入并退出
  static Future<T> pushAndReplace<T,T0>(BuildContext context,Widget widget,{String pushRouteName,T0 result}){
    if(widget == null){
      return Future(null);
    }
    //省缺路由名
    if (StringUtils.isEmpty(pushRouteName)) {
      pushRouteName = widget?.runtimeType?.toString();
    }
    return Navigator.of(context).pushReplacement<T,T0>(
        _MyCupertinoPageRoute(
            settings: RouteSettings(name: pushRouteName),
            builder: (context) =>widget),result:result );
  }

  ///压入并压出上一级
  static Future<T> pushAndPop<T,T0>(BuildContext context,Widget widget,{String pushRouteName,T0 result}){
    if(widget == null){
      return Future(null);
    }
    //省缺路由名
    if (StringUtils.isEmpty(pushRouteName)) {
      pushRouteName = widget?.runtimeType?.toString();
    }
    return Navigator.of(context).pushReplacement<T,T0>(
        _MyCupertinoPageRoute(
            settings: RouteSettings(name: pushRouteName),
            builder: (context) =>widget),result: result);
  }
}

/// ios风格右进右出的路由动画
class _MyCupertinoPageRoute<T> extends CupertinoPageRoute<T> {
  _MyCupertinoPageRoute({
    WidgetBuilder builder,
    String title,
    RouteSettings settings,
    bool maintainState = true,
    bool fullscreenDialog = false,
  })  : assert(builder != null),
        assert(maintainState != null),
        assert(fullscreenDialog != null),
        assert(opaque),
        super(
          settings: settings,
          fullscreenDialog: fullscreenDialog,
          builder: builder);

  @override
  Duration get transitionDuration => const Duration(milliseconds: 600);
}

/// 渐变跳转
class _GradualRouteBuilder extends PageRouteBuilder {
  // 跳转的页面
  final Widget widget;

  _GradualRouteBuilder(this.widget)
      : super(
      transitionDuration: Duration(milliseconds: 500),
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return widget;
      },
      transitionsBuilder: (BuildContext context,
          Animation<double> animation,
          Animation<double> secondaryAnimation,
          Widget child) {
        return FadeTransition(
            child: child,
            opacity: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
                parent: animation, curve: Curves.fastOutSlowIn)));
      });
}